import React, { useState, useEffect } from 'react';
import { Input, Button, Space, message, Form } from 'antd';
import http from '../utils/request';
import { useNavigate } from 'react-router-dom';

// 手机号校验规则
const phoneNumberValidator = (_, value) => {
    const phoneReg = /^1[3-9]\d{9}$/;
    if (!value) {
        return Promise.reject('请输入您的手机号！');
    }
    if (!phoneReg.test(value)) {
        return Promise.reject('手机号格式不正确');
    }
    return Promise.resolve();
};

// 验证码校验规则
const verificationCodeValidator = (_, value) => {
    const codeReg = /^\d{4}$/;
    if (!value) {
        return Promise.reject('请输入验证码！');
    }
    if (!codeReg.test(value)) {
        return Promise.reject('验证码格式不正确，请输入4位数字验证码');
    }
    return Promise.resolve();
};

export default function AuthCode({ isRadioChecked }) {
    const [messageApi, contextHolder] = message.useMessage();
    const [phoneNumber, setPhoneNumber] = useState('');
    const [frontendCode, setFrontendCode] = useState('');
    const [backendCode, setBackendCode] = useState('');
    const [countdown, setCountdown] = useState(0); // 倒计时状态
    const [isButtonDisabled, setIsButtonDisabled] = useState(false); // 控制按钮禁用
    const navigate = useNavigate()
    const getCode = async () => {
        if (countdown > 0) return; // 如果倒计时中，不允许重新获取验证码

        let res = await http.post('/sendCode', { phoneNumber });
        let { code, message, flag, id, accessToken, refreshToken } = res.data;
        localStorage.setItem('accessToken', accessToken); // 存储访问令牌
        localStorage.setItem('refreshToken', refreshToken); // 存储刷新令牌
        sessionStorage.setItem('id', id);
        setBackendCode(code);
        messageApi.open({
            type: flag ? 'success' : 'error',
            content: message,
        });

        // 启动倒计时
        setCountdown(60);
        setIsButtonDisabled(true);
    };

    useEffect(() => {
        let timer;
        if (countdown > 0) {
            timer = setInterval(() => {
                setCountdown((prev) => prev - 1);
            }, 1000);
        } else {
            setIsButtonDisabled(false);
        }

        return () => clearInterval(timer); // 清除定时器
    }, [countdown]);

    const handleLogin = async () => {
        if (isRadioChecked) {
            if (phoneNumber && frontendCode) {
                if (frontendCode === backendCode) {
                    messageApi.open({
                        type: 'success',
                        content: '登录成功',
                    });
                    navigate('/home')
                } else {
                    messageApi.open({
                        type: 'error',
                        content: '验证码错误，请重试',
                    });
                }
            } else {
                messageApi.open({
                    type: 'error',
                    content: '请输入手机号和验证码',
                });
            }
        } else {
            messageApi.open({
                type: 'error',
                content: '请先阅读并选中用户隐私政策',
            });
        }
    };

    return (
        <>
            {contextHolder}
            <div>
                <div className='form-item'>
                    <Form
                        name="login"
                        initialValues={{ phonenumber: phoneNumber }}
                        onFinish={handleLogin}
                        style={{
                            maxWidth: 360,
                        }}
                    >
                        <Form.Item
                            name="phonenumber"
                            rules={[{ validator: phoneNumberValidator }]}
                        >
                            <Input
                                size="large"
                                placeholder="请输入手机号"
                                onChange={(e) => { setPhoneNumber(e.target.value) }}
                            />
                        </Form.Item>

                        <Form.Item
                            name="verificationCode"
                            rules={[{ validator: verificationCodeValidator }]}
                        >
                            <Space.Compact>
                                <Input
                                    placeholder="请输入验证码"
                                    size="large"
                                    value={frontendCode}
                                    onChange={(e) => { setFrontendCode(e.target.value) }}
                                />

                                <Button
                                    id='getcode-btn'
                                    onClick={getCode}
                                    size="large"
                                    disabled={isButtonDisabled} // 根据倒计时禁用按钮
                                >
                                    {countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码'}
                                </Button>
                            </Space.Compact>
                        </Form.Item>
                    </Form>
                </div>

                <div className='form-item'>
                    <Button type="primary" size="large" block onClick={handleLogin}>
                        登录
                    </Button>
                </div>
            </div>
        </>
    );
}
